package com.tedu._06weibo.controller;

import com.tedu._06weibo.mapper.WeiboMapper;
import com.tedu._06weibo.pojo.dto.WeiboDTO;
import com.tedu._06weibo.pojo.entity.User;
import com.tedu._06weibo.pojo.entity.Weibo;
import com.tedu._06weibo.pojo.vo.WeiboDetailVO;
import com.tedu._06weibo.pojo.vo.WeiboIndexVO;
import com.tedu._06weibo.result.JsonResult;
import com.tedu._06weibo.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/weibo")
@Api(tags = "微博模块")
@Validated
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;
    @PostMapping("/insert")
    @ApiOperation("发布微博")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user==null){
            return new JsonResult(Status.NOT_LOGIN);
        }

        Weibo weibo = new Weibo();
        weibo.setContent(weiboDTO.getContent());
        weibo.setUserId(user.getId());
        weibo.setCreated(new Date());
        weiboMapper.insert(weibo);
        return JsonResult.success();
    }

    @GetMapping("/selectIndex")
    @ApiOperation("首页微博列表")
    public JsonResult findIndexWeibo(){
        return JsonResult.success(weiboMapper.selectIndex());
    }

    @GetMapping("/selectById")
    @ApiOperation("微博详情")
    @ApiImplicitParam(value = "微博ID",name = "id",required = true,example = "1")
    public JsonResult findById(@Range(min = 1,max = 999,message = "微博ID必须在1-999之间") @RequestParam Integer id){
        if (id<=0){
            throw new IllegalArgumentException("微博ID小于1");
        }
        return JsonResult.success(weiboMapper.selectById(id));
    }
}
